//
//  ExamineOneDetailViewController.m
//  LoanOne
//
//  Created by WangZhenyu on 2017/10/26.
//  Copyright © 2017年 WangZhenyu. All rights reserved.
//

#import "ExamineOneDetailViewController.h"
#import "GlobalFunction.h"
#import "UIActionSheet+Blocks.h"
#import "ExamineOneSuccessViewController.h"
#import "MBProgressHUD.h"
#import "Base64.h"
#import "UserManger.h"
#import "UserInfo.h"

@interface ExamineOneDetailViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>{
    NSInteger type; //1身份证正面 2身份证反面
}
@property (weak, nonatomic) IBOutlet UITextField *oneTextField;
@property (weak, nonatomic) IBOutlet UITextField *twoTextField;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIImageView *zhengImageView;
@property (weak, nonatomic) IBOutlet UIImageView *fanImageView;

@end

@implementation ExamineOneDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"填写资料";
    [self addBlackBackBtn];
    [self.sureBtn setBackgroundImage:getColorToImage(ThemeColor) forState:UIControlStateNormal];
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.contentSize = CGSizeMake(0, 508);
    
    [self.scrollView setFrame:CGRectMake(0, 64 + IS_iPhoneX_Top, SCREEN_WIDTH_DEVICE, SCREEN_HEIGHT_DEVICE - 64 - IS_iPhoneX_Top - 44 - IS_iPhoneX_Bottom)];
    [self.sureBtn setFrame:CGRectMake(0, SCREEN_HEIGHT_DEVICE - 44 - IS_iPhoneX_Bottom, SCREEN_WIDTH_DEVICE, 44 + IS_iPhoneX_Bottom)];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)zhengPress {
    type = 1;
    [self chooseTakePhoto:@"上传身份证正面照片"];
}

- (IBAction)fanPress {
    type = 2;
    [self chooseTakePhoto:@"上传身份证反面照片"];
}

- (IBAction)surePress {
    if (self.oneTextField.text.length == 0) {
        [self showHUDAlert:@"请填写真实姓名"];
        return;
    }
    if (self.twoTextField.text.length == 0) {
        [self showHUDAlert:@"请填写身份证号码"];
        return;
    }
    if ([self.zhengImageView.image isEqual:[UIImage imageNamed:@"tianxie_fan_btn"]]) {
        [self showHUDAlert:@"请上传身份证正面照"];
        return;
    }
    if ([self.fanImageView.image isEqual:[UIImage imageNamed:@"tianxie_zheng_btn"]]) {
        [self showHUDAlert:@"请上传身份证反面照"];
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.label.text = @"正在提交";
    
    UserInfo *user = [UserManger currentLoggedInUser];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:self.qixian forKey:@"duration"];
    [dic setObject:[NSNumber numberWithFloat:self.amount] forKey:@"requireAmount"];
    [dic setObject:self.oneTextField.text forKey:@"name"];
    [dic setObject:self.twoTextField.text forKey:@"identificationNumber"];
    [dic setObject:user.phone forKey:@"mobile"];
    [dic setObject:[UIImageJPEGRepresentation(self.zhengImageView.image, 0.5) base64EncodedString] forKey:@"idFrontImg"];
    [dic setObject:[UIImageJPEGRepresentation(self.fanImageView.image, 0.5) base64EncodedString] forKey:@"idBackImg"];
    
    [[ServiceRequest sharedService] POSTJSON:@"newloan" parameters:dic success:^(id responseObject) {
        [hud hideAnimated:YES];
        ExamineOneSuccessViewController *viewCon = [[ExamineOneSuccessViewController alloc] initWithNibName:@"ExamineOneSuccessViewController" bundle:nil];
        [self.navigationController pushViewController:viewCon animated:YES];
    } failure:^(NSString *error, NSInteger code) {
        [hud hideAnimated:YES];
        [self showHUDAlert:error];
    } update:^(float progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = progress;
        });
    }];
}

- (void)chooseTakePhoto:(NSString *)str{
    if (IOS8_OR_LATER) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:str message:nil preferredStyle: UIAlertControllerStyleActionSheet];
        [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self changeHeadPortraitCamera];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self changeHeadPortraitFromPicture];
        }]];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        //弹出提示框；
        [self.navigationController presentViewController:alert animated:true completion:nil];
    }else{
        [UIActionSheet showInView:self.navigationController.topViewController.view
                        withTitle:str
                cancelButtonTitle:@"取消"
           destructiveButtonTitle:nil
                otherButtonTitles:@[@"拍照", @"从手机相册选择"]
                         tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex){
                             if (buttonIndex == 0) {
                                 [self changeHeadPortraitCamera];
                             }else if (buttonIndex == 1){
                                 [self changeHeadPortraitFromPicture];
                             }
                         }];
    }
}

#pragma mark 拍照
-(void)changeHeadPortraitCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    [self addImagePickerController:sourceType];
}
#pragma mark 从相册中选取
-(void)changeHeadPortraitFromPicture
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self addImagePickerController:sourceType];
}

#pragma mark 选择相册
-(void)addImagePickerController:(UIImagePickerControllerSourceType )sourceType
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.sourceType = sourceType;
    [self.navigationController.topViewController presentViewController:picker animated:YES completion:nil];
}

#pragma mark 选择相册完毕
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    if (type == 1) {
        self.zhengImageView.image = image;
    }else if (type == 2){
        self.fanImageView.image = image;
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
